package com.sdhs.workflow.flowable.listener;

import com.sdhs.common.core.domain.entity.SysUser;
import com.sdhs.common.core.domain.model.LoginUser;
import com.sdhs.common.utils.SecurityUtils;
import com.sdhs.common.utils.spring.SpringUtils;
import com.sdhs.system.mapper.SysUserMapper;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;
import org.flowable.engine.impl.el.FixedValue;

import java.util.List;

// 处理流程节点执行器监听：角色 按部门分配审批人
@Component
public class RolePromoterDeptExecutionListener  implements ExecutionListener {

    // 角色id
    private FixedValue roleId;
    // 变量名称
    private FixedValue varName;

    @Override
    public void notify(DelegateExecution execution) {
        SysUserMapper userMapper = SpringUtils.getBean(SysUserMapper.class);

        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = new SysUser();
        user.setRoleId(Long.valueOf((String) roleId.getValue(execution)));
        List<SysUser> suserList = userMapper.selectAllocatedList(user);

        StringBuilder userIds = new StringBuilder();
        for (SysUser sysUser : suserList) {
            if(sysUser.getDeptId().equals(loginUser.getDeptId())){
                userIds.append(sysUser.getUserId()).append(",");
            }
        }
        if(!userIds.isEmpty()){
            userIds.setLength(userIds.length() - 1);
        }
        execution.setVariable((String) varName.getValue(execution), userIds);
    }

    // setter方法用于接收XML配置的参数
    public void setRoleId(FixedValue roleId) {
        this.roleId = roleId;
    }

    // setter方法用于接收XML配置的参数
    public void setVarName(FixedValue varName) {
        this.varName = varName;
    }
}
